package com.fruitsales.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 公共过滤器
 */
public class CommonFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {

		//转换为子接口的类型
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;		
		
		//统一设置请求和响应编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//设置允许其他域发出跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		/*****用户登陆验证*****/	
		
		String uri = request.getRequestURI(); //获得请求uri
		/*System.out.println(uri);*/
		
		String context = request.getContextPath();//获得web应用根目录路径
		/*System.out.println(context);*/
				
		if (!uri.equals(context + "/")
				&&!uri.equals(context + "/login.html")
				&&!uri.equals(context + "/Register.html")
				&&!uri.equals(context + "/Rules.txt")
				&& !uri.equals(context + "/logout.jsp")
				&& !uri.equals(context + "/user/login")
				&& !uri.startsWith(context + "/AmazeUI-2.4.2")
				&& !uri.startsWith(context + "/css")
				&& !uri.startsWith(context + "/js")
				&& !uri.startsWith(context + "/images")	) {
			
			//判断用户是否登陆过
			HttpSession session = request.getSession();
			
			String LoginName = (String) session.getAttribute("LoginName"); 
			
			if (LoginName == null) {
				
				//判断是ajax请求还是正常请求
				if (request.getHeader("X-Requested-With") != null &&
						request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
					//通知浏览器session超时，设置一个特殊的报头信息，让前端做判断
					response.setHeader("sessionStatus", "timeout");		
					
					return;
				} 										
				
			}
			
		}				
				
		//继续执行请求		
		chain.doFilter(req, resp);		
	}

	public void init(FilterConfig fConfig) throws ServletException {

	}

}